import httplib, os

global progress; progress = 0.0

def post_multipart(host, selector, fields, files):
    """
    Post fields and files to an http host as multipart/form-data.
    fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files
    Return the server's response page.
    """
    BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
    h = httplib.HTTP(host)
    h.putrequest('POST', selector)
    h.putheader('content-type','multipart/form-data; boundary=%s' % BOUNDARY)
    h.putheader('content-length', str(38 + sum(81 + len(name) + len(value) for name,value in fields) + sum(134 + len(name) + len(filename) + os.path.getsize(filepath) for name,filename,filepath in files)))
    h.endheaders()
    encode_multipart_formdata(h, BOUNDARY, fields, files)
    errcode, errmsg, headers = h.getreply()
    return h.file.read()

def encode_multipart_formdata(L, BOUNDARY, fields, files):
	"""
	L is an http connection.
	BOUNDARY is a BOUNDARY (DUH!).
	fields is a sequence of (name, value) elements for regular form fields.
	files is a sequence of (name, filename, value) elements for data to be uploaded as files
	"""
	CRLF = '\r\n'
	for (key, value) in fields:
		L.send('--' + BOUNDARY) # 2 + 2 + len(BOUNDARY)
		L.send(CRLF)
		L.send('Content-Disposition: form-data; name="%s"' % key) # 2 + 39 + len(key)
		L.send(CRLF)
		L.send(CRLF)
		L.send(value) # 2 + len(value)
		L.send(CRLF)
	for (key, filename, value) in files:
		fp = file(value,"rb")
		size = os.path.getsize(value)
		L.send('--' + BOUNDARY)
		L.send(CRLF)
		L.send('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
		L.send(CRLF)
		L.send('Content-Type: %s' % get_content_type(filename))
		L.send(CRLF)
		L.send(CRLF)
		#L.send(value)
	data = fp.read(1024)
	global progress
	
	while (data):
		L.send(data)
		data = fp.read(1024)
		L.send(CRLF)
		#progress = fp.tell()*100.0/size
	L.send('--' + BOUNDARY + '--')
	L.send(CRLF)
	progress = 100.0

def get_content_type(filename):
	#return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
	return 'application/octet-stream'
